package com.baicaoyuan.web.service;

import com.baicaoyuan.web.common.PlatformIdConfig;
import com.baicaoyuan.web.common.StringUtils;
import com.baicaoyuan.web.common.excel.ProfitInput;
import com.baicaoyuan.web.common.relation.RelationCache;
import com.baicaoyuan.web.model.*;
import com.baicaoyuan.web.repository.*;
import com.baicaoyuan.web.response.*;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述：
 *
 * @author 罗富祥
 * 创建时间： 2018/1/4
 */
@Service
public class JzzService {

    @Autowired
    PlatformIdConfig platformIdConfig;

    @Autowired
    JzzUserRepository jzzUserRepository;

    @Autowired
    JzzUserProjectRepository jzzUserProjectRepository;

    @Autowired
    ProjectRepository projectRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    JzzProfitInputRepository jzzProfitInputRepository;

    @Autowired
    JzzProfitFlowRepository jzzProfitFlowRepository;

    @Autowired
    JzzCurveRepository jzzCurveRepository;
    @Autowired
    RelationCache relationCache;


    public JzzUserResponse findJzzUser(Long userId) {
        JzzUserResponse response = new JzzUserResponse();

        JzzUserDO jzzUser = jzzUserRepository.findByUserId(userId);
        BeanUtils.copyProperties(jzzUser, response);

        UserDO user = userRepository.getOne(userId);
        response.setUserName(user.getRealName());

        JzzCurveDO curve = jzzCurveRepository.findTopOrderByIdDesc();
        response.setCurrentPrice(curve.getPrice());
        return response;
    }

    /**
     * 创建jzz用户
     *
     * @param userId
     * @return
     */
    @Transactional
    public boolean createJzzUser(Long userId, Long projectId, String serialNumber) throws Exception {
        ProjectDO projectDO = projectRepository.findOne(projectId);
        if (projectDO.getJoinJzz() == 0) {
            throw new Exception("不是金钟子项目！存在异常");
        }

        JzzUserDO jzzUserDO = jzzUserRepository.findByUserId(userId);
        if (jzzUserDO == null) {
            JzzUserDO jzzUser = new JzzUserDO();
            jzzUser.setUserId(userId);
            jzzUser.setStatus("1");
            jzzUserRepository.save(jzzUser);
        }

        JzzUserProjectDO jzzUserProject = new JzzUserProjectDO();
        jzzUserProject.setProjectId(projectId);
        jzzUserProject.setUserId(userId);
        jzzUserProject.setSerialNumber(serialNumber);
        jzzUserProjectRepository.save(jzzUserProject);

        Integer r = userRepository.updateType(userId, 1);
        return Boolean.TRUE;
    }


    @Transactional
    public boolean saveProfitInput(List<ProfitInput> inputs, Long userId) {

        if (CollectionUtils.isEmpty(inputs)) {
            return false;
        }
        List<JzzProfitInputDO> inputDOList = Lists.newArrayListWithCapacity(inputs.size());


        inputs.forEach(i -> {
            JzzUserProjectDO jup = jzzUserProjectRepository.findBySerialNumber(i.getSno());
            if (jup != null) {
                JzzProfitInputDO inputDO = new JzzProfitInputDO();
                inputDO.setPeriodNo(i.getPeriodNo());
                inputDO.setSerialNumber(i.getSno());
                inputDO.setTotalProfit(BigDecimal.valueOf(Double.parseDouble(i.getProfit())));

                BigDecimal percentGrow = BigDecimal.valueOf(platformIdConfig.getPercent_grow());
                BigDecimal growProfit = inputDO.getTotalProfit().multiply(percentGrow);

                BigDecimal percentMyself = BigDecimal.valueOf(platformIdConfig.getPercent_myself());
                BigDecimal myselfProfit = inputDO.getTotalProfit().multiply(percentMyself);

                BigDecimal percentDirect = BigDecimal.valueOf(platformIdConfig.getPercent_direct());
                BigDecimal directProfit = inputDO.getTotalProfit().multiply(percentDirect);

                BigDecimal percentIndirect = BigDecimal.valueOf(platformIdConfig.getPercent_indirect());
                BigDecimal indirectProfit = inputDO.getTotalProfit().multiply(percentIndirect);

                BigDecimal percentTeamLeader = BigDecimal.valueOf(platformIdConfig.getPercent_teamleader());
                BigDecimal teamLeaderProfit = inputDO.getTotalProfit().multiply(percentTeamLeader);

                inputDO.setPercentGrowProfit(growProfit);
                inputDO.setPercentMyselfProfit(myselfProfit);
                inputDO.setPercentDirectProfit(directProfit);
                inputDO.setPercentIndirectProfit(indirectProfit);
                inputDO.setPercentTeamLeaderProfit(teamLeaderProfit);
                inputDO.setOperator(userId);
                inputDOList.add(inputDO);
            }
        });
        return jzzProfitInputRepository.save(inputDOList).size() > 0;
    }

    /**
     * 根据状态获取excel导入期号
     *
     * @return
     */
    public List<String> getDistinctPeriodNo(Integer status) {
        return jzzProfitInputRepository.getDistinctPeriodNo(status);
    }

    /**
     * 审核利润
     *
     * @param periodNos
     * @param status
     * @return
     */
    public boolean checkProfit(List<String> periodNos, Integer status) {
        return jzzProfitInputRepository.checkProfit(periodNos, status) > 0;
    }

    public boolean revertProfit(List<String> periodNos, Integer status) {
        return jzzProfitInputRepository.revertProfit(periodNos, status) > 0;
    }

    public Integer getCountOfAll(Integer status, String periodNo, String serialNumber) {
        Integer count;
        if (status == null) {
            count = jzzProfitInputRepository.countAllByPeriodNoLikeAndSerialNumberLike(periodNo, serialNumber);
        } else {
            count = jzzProfitInputRepository.countAllByStatusAndPeriodNoLikeAndSerialNumberLike(status, periodNo, serialNumber);
        }
        return count;
    }

    public List<JzzProfitInputResponse> getJzzProfitInput(Integer status, String periodNo, String serialNumber, Integer page, Integer pageSize) {

        List<JzzProfitInputDO> list;
        Integer start = (page - 1) * pageSize;
        Integer end = pageSize;
        if (status == null) {

            list = jzzProfitInputRepository.queryJzzProfitInput(periodNo, serialNumber, start, end);
        } else {
            list = jzzProfitInputRepository.queryJzzProfitInput(status, periodNo, serialNumber, start, end);
        }


        List<JzzProfitInputResponse> result = new ArrayList<>();
        if (list != null) {
            list.forEach(x -> {
                JzzProfitInputResponse response = new JzzProfitInputResponse();
                BeanUtils.copyProperties(x, response);
                if (status == 2) {
                    List<JzzProfitFlowDO> flowsDO = jzzProfitFlowRepository.findByJzzProfitInputId(x.getId());
                    List<JzzProfitFlowResponse> flows = Lists.newArrayList();
                    flowsDO.forEach(y -> {
                        JzzProfitFlowResponse flow = new JzzProfitFlowResponse();
                        BeanUtils.copyProperties(y, flow);

                        UserDO user = userRepository.findOne(flow.getUserId());
                        UserResponse userResponse = new UserResponse();
                        BeanUtils.copyProperties(user, userResponse);
                        flow.setUser(userResponse);
                        flows.add(flow);
                    });
                    response.setFlows(flows);
                }
                result.add(response);
            });
        }
        return result;
    }


    public Integer getCountJzzUser(Long userId) {
        Integer count;
        if (userId == null) {
            count = jzzUserRepository.countAllBy();
        } else {
            count = jzzUserRepository.countAllByUserId(userId);
        }
        return count;
    }

    public List<JzzUserInfoResponse> getJzzUsers(Long userId,String phone, Integer page, Integer pageSize) {
        List<JzzUserDO> list;
        if (StringUtils.isNullOrEmpty(phone)) {
            list = jzzUserRepository.queryUsers((page - 1) * pageSize, pageSize);
        } else {
            list = jzzUserRepository.queryByUserPhone(phone, (page - 1) * pageSize, pageSize);
        }

        List<JzzUserInfoResponse> result = new ArrayList<>();
        list.forEach(x -> {
            JzzUserInfoResponse response = new JzzUserInfoResponse();
            BeanUtils.copyProperties(x, response);
            UserDO user = userRepository.getOne(x.getUserId());
            response.setUserName(user.getRealName());
            response.setPhone(user.getTelephone());

            //设备号名下
            List<JzzUserProjectDO> userProjectDOList = jzzUserProjectRepository.findByUserIdAndStatus(x.getUserId(), "1");
            if (!CollectionUtils.isEmpty(userProjectDOList)) {
                Map<String, String> map = new HashMap<>();
                for (JzzUserProjectDO p : userProjectDOList) {
                    map.put(p.getSerialNumber(), projectRepository.findOne(p.getProjectId()).getName());
                }
                response.setSno(map);
            }
            //response.setFlows(findFlowsByUserId(x.getUserId()));

            //是否团长
            relationCache.checkTeamLeader(x.getUserId());

            result.add(response);
        });
        return result;
    }

    public List<JzzUserProfitFlowResponse> findFlowsByUserId(Long userId) {
        List<JzzUserProfitFlowResponse> flows = Lists.newArrayList();
        //分润明细
        List<JzzProfitFlowDO> flowsDO = jzzProfitFlowRepository.findByUserId(userId);
        if (flowsDO != null && flowsDO.size() > 0) {
            flowsDO.forEach(y -> {
                JzzUserProfitFlowResponse flow = new JzzUserProfitFlowResponse();
                BeanUtils.copyProperties(y, flow);
                JzzUserProjectDO fromUser = jzzUserProjectRepository.findBySerialNumber(y.getSerialNumber());
                if (fromUser == null) {
                    System.out.println(y.getSerialNumber());
                }
                UserDO u = userRepository.findOne(fromUser.getUserId());
                User1Response userResponse = new User1Response();
                BeanUtils.copyProperties(u, userResponse);
                flow.setUser(userResponse);
                flows.add(flow);
            });
        }
        return flows;
    }

    public List getSumJzz() {
        return jzzProfitFlowRepository.getSumJzz();
    }

    public List getJzz30Price() {
        return jzzCurveRepository.getSum30Price();
    }
}

